package com.example.asynctask;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.Activity;
import android.database.CursorJoiner.Result;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {
	
	EditText et;
	TextView tv;
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        et = (EditText)findViewById(R.id.editText1);
        tv = (TextView)findViewById(R.id.textView1);
        et.setText("itcaffe.cafe24.com/android_test/member_list.jsp");
    }
    
    public void goPage(View view) {
    	
    	String url = et.getText().toString();
    	if(url.indexOf("http://") == -1){
    		url = "http://"+url;
    	}
    	new DownloadTask().execute(url);
		
		//itcaffe.cafe24.com/android_test/member_list.jsp
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
    
    class DownloadTask extends AsyncTask<String, String, String> {
    	
    	StringBuilder sb = new StringBuilder();
    	
    	@Override
    	protected String doInBackground(String... params) {
    		download((String)params[0]);
    		return null;
    	}
    	
    	@Override
    	protected void onPostExecute(String result) {
    		
    		tv.setText(sb.toString());
    		super.onPostExecute(result);
    	}
    	
    	public void download(String url){
    		
			HttpURLConnection conn = null;
			
			try {
				URL u = new URL(url);
				conn = (HttpURLConnection)u.openConnection();
				InputStream is = conn.getInputStream();
				InputStreamReader isr = new InputStreamReader(is);
				BufferedReader br = new BufferedReader(isr);
				
				while(true){
					String str = br.readLine();
					if(str == null) {
						break;
					}
					sb.append(str);
					sb.append("\n");
				}
				
			} catch (Exception e) {
				
			} finally {
				conn.disconnect();
			}
		}
    }
}

